const mongoose = require('mongoose')
const db = 'mongodb://localhost/douban-koa'

const glob = require('glob')
const { resolve } = require('path')

mongoose.Promise = global.Promise

exports.initSchemas = () => {
    glob.sync(resolve(__dirname, './schema', '**/*.js')).forEach(require)
}


// 创建管理员账户
exports.initAdmin = async() => {
    const User = mongoose.model('User')
    let user = await User.findOne({
        username: 'Jace'
    })
    if (!user) {
        const user = new User({
            username: 'Jace',
            email: 'jace@qq.com',
            password: '1234'
        })

        await user.save()
    }
}

exports.connect = () => {

    let maxConnectTimes = 0

    return new Promise((resolve, reject) => {
        if (process.env.NODE_ENV != 'production') {
            mongoose.set('debug', true)
        }

        // mongoose.set('debug', true)

        mongoose.connect(db)

        mongoose.connection.on('disconnected', () => {
            // mongoose.connect(db)
            maxConnectTimes++
            if (maxConnectTimes < 5) {
                mongoose.connect(db)
            } else {
                throw new Error('数据库挂了吧，快去修吧')
                // reject('数据库挂了吧，快去修吧')
            }
        })

        mongoose.connection.on('error', err => {
            maxConnectTimes++
            if (maxConnectTimes < 5) {
                mongoose.connect(db)
            } else {
                throw new Error('数据库挂了吧，快去修吧')
                // reject('数据库挂了吧，快去修吧')
            }
        })

        mongoose.connection.once('open', () => {

            // const Dog = mongoose.model('Dog', { name: String })
            // const doga = new Dog({ name: '阿法狗' })
            // doga.save().then(() => {
            //     console.log('wang')
            // })

            resolve()
            console.log('MongoDB connected successfully')
        })


    })
}